package com.woniuxy.intercepts;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author: 马宇航
 * @Todo: 定义一个权限拦截器
 * @DateTime: 25/08/06/星期三 16:49
 * @Component: 成都蜗牛学苑
 **/
public class PermsInterceptor implements HandlerInterceptor {
    /**
     * 进入Controller之前的拦截器
     * ChangeLog : 1. 创建 (25/08/06/星期三 16:54 [马宇航]);
     * @param request
     * @param response
     * @param handler  controller的方法
     * @return boolean
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.handler 就是进入的controller的方法
        if(handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) handler;
            //2.获取方法上的注解
            WoniuPerm perm = method.getMethodAnnotation(WoniuPerm.class);
            if(perm==null){
                //没有配置i权限 注解就直接放行
                return true;
            }
            //3.拿到对应的配置的权限值
            String value = perm.value();
            //4.判断value的值是否和当前用户的值一样
            String token = request.getHeader("Authorization");
            //5. token去redis中获取当前登录的用户信息 （之前的登录缺少了，权限和角色的缓存）
            //6. 略 用户角色权限的查询，也不用遍历，先写死
            if("user::delete".equals(value)){
                return true;
            }else{
                response.sendError(304,"没有访问权限");
                return false;
            }
        }else {
            //7. 其他的方法，都放行
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
